import dayjs from 'dayjs';
import logger from './logger';
import buffer from '@ohos.buffer';
import window from '@ohos.window';
import cryptoJS from '@ohos/crypto-js';
import Match from '../model/common/Match';
import promptAction from '@ohos.promptAction';
import common from '@ohos.app.ability.common';
import display from '@ohos.display';
import WindowModel from '../model/WindowModel'

export class utils {


  private windowRect: WindowModel = new WindowModel(display.getDefaultDisplaySync().width, display.getDefaultDisplaySync().height)

  landscapeBarWidth(): number {
    return 100;
  }
  landscapeBarHeight(): number {
    return 100;
  }

  isLandscapeDevice(): boolean {
    return display.getDefaultDisplaySync().width > display.getDefaultDisplaySync().height
  }

  setWindowRect(width: number, height: number) {
    this.windowRect.width = width
    this.windowRect.height = height
  }

  getWindowRect(): WindowModel {
    return this.windowRect
  }

  defaultPlayVideoWidth(): number {
    return this.displayWidth() - 360;
  }


  videoCardHeight(): number {
    return 200;
  }

  playPageBarWidth() {
    return 360;
  }

  deviceWidth(): number {
    return display.getDefaultDisplaySync().width
  }

  deviceHeight(): number {
    return display.getDefaultDisplaySync().height
  }

  displayHeight(): number {
    return this.getWindowRect().height
  }

  displayWidth(): number {
    return this.getWindowRect().width
  }

  isLandscape(): boolean {
    return this.getWindowRect().width > this.getWindowRect().height
  }

  changeOrientation(context: common.Context, isLandscape: boolean) {
    window.getLastWindow(context).then((lastWindow) => {
      lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT);
    });
  }

  async setSystemBarShowHide(context: common.Context, show: boolean) {
    let windowClass = await window.getLastWindow(context);
    if (!show)
      await windowClass.setWindowSystemBarEnable([]);
    else
      await windowClass.setWindowSystemBarEnable(["status", "navigation"]);
  }

  formatNumber(num: number | string | undefined | null): string {
    if (Number.isNaN(num)) {
      return '';
    } else {
      const realNum = typeof num === 'string' ? Number.parseInt(num) : num
      if (realNum < 10000) {
        return realNum.toString();
      } else if (realNum < 100000000) {
        return (realNum / 10000).toFixed(1) + '万';
      } else {
        return (realNum / 100000000).toFixed(1) + '亿';
      }
    }
  }

  formatDateAsYMDHmCN(date: Date | number | undefined | null): string {
    if (date == null)
      return '';
    const hour = Number.parseInt(dayjs(date).format('HH'));
    const minute = Number.parseInt(dayjs(date).format('mm'));
    return dayjs(date).format('YYYY年MM月DD日') + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute);
  }

  formatTimeDiff(date: Date | number | undefined | null): string {
    if (date == null)
      return '';
    const now = dayjs();
    const diff = now.diff(date, 'minute');
    if (diff < 60)
      return `${diff}分钟前`;
    else if (diff < 24 * 60)
      return `${Math.floor(diff / 60)}小时前`;
    return dayjs(date).format('MM月DD日');
  }

  setLayoutFullScreen(windowStage: window.WindowStage, statusBarColor: string, statusBarContentColor: string,
    navigationBarColor: string, navigationBarContentColor: string) {
    let windowClass = null;
    windowStage.getMainWindow((err, data) => {
      if (err.code) return;
      windowClass = data;
      let isLayoutFullScreen = false;
      windowClass.setWindowLayoutFullScreen(isLayoutFullScreen);
      let sysBarProps = {
        statusBarColor: statusBarColor,
        statusBarContentColor: statusBarContentColor,
        navigationBarColor: navigationBarColor,
        navigationBarContentColor: navigationBarContentColor
      };
      windowClass.setWindowSystemBarProperties(sysBarProps);
    })
  }

  regexMatch(input: string, reg: RegExp): Match {
    let output;
    try {
      let ms = input.match(reg);
      let res = ms[1].toString();
      if (this.isEmpty(res))
        output = new Match(false, '');
      else
        output = new Match(true, res);
    } catch (e) {
      logger.error(e);
      output = new Match(false, '');
    }
    return output;
  }

  md5(str) {
    return cryptoJS.MD5(str).toString()
  }

  uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  getQuery(url: string) {
    var index = url.indexOf('?');
    if (index > 0)
      return url.substring(index);
    return '';
  }

  parse<T>(json: string): T {
    let result: T = JSON.parse(json) as T;
    return result;
  }

  toJson(obj: any): string {
    return JSON.stringify(obj);
  }

  isEmpty(obj: any): boolean {
    if (typeof obj == 'undefined' || obj == null || obj?.toString().trim() == '')
      return true;
    return false;
  }

  buvid(): string {
    var mac = [];
    for (let i = 0; i < 6; i++) {
      var min = Math.min(0, 0xff)
      var max = Math.max(0, 0xff)
      var num = parseInt((Math.random() * (min - max + 1) + max).toString()).toString(16)
      mac.push(num)
    }
    var md5 = this.md5(mac.join(':'));
    var md5Arr = md5.split('');
    return `XY${md5Arr[2]}${md5Arr[12]}${md5Arr[22]}${md5}`
  }

  showPopup(msg: string, duration?: number) {
    if (this.isEmpty(duration))
      duration = 2000;
    promptAction.showToast({
      message: msg,
      duration: duration,
    });
  }

  stringForTime(timeMs: any): string {
    try {
      let totalSeconds = (timeMs / 1000);
      let seconds = totalSeconds % 60;
      let minutes = (totalSeconds / 60) % 60;
      let hours = totalSeconds / 3600;
      hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
      minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
      seconds = this.completionNum(Math.floor(Math.floor(seconds * 100) / 100));
      if (hours > 0)
        return hours + ":" + minutes + ":" + seconds;
      else
        return minutes + ":" + seconds;
    } catch (e) {
      logger.error(e);
      return '';
    }
  }

  completionNum(num: any): any {
    if (num < 10)
      return '0' + num;
    else
      return num;
  }

  arrayBufferToBase64(arrayBuffer: ArrayBuffer) {
    const buff = buffer.from(arrayBuffer);
    const base64String = buff.toString('base64');
    return base64String;
  }
}
export default new utils();